
const request = require('./request.js');
const config = require('./config.js');

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const setShareAppMessage = () => {
  return {
    title: '有局',
    path: 'pages/index/index',
    imageUrl: 'https://hudongyjp.oss-cn-hangzhou.aliyuncs.com/smarthomeworkminiprogram/shareImage.jpg'
  }
}
/** 
 * 拉起APP复制文字内容
 */
const launchAppCopy = () => {
  wx.vibrateShort();  //短震动
  wx.setClipboardData({
    data: 'https://apps.apple.com/cn/app/id1532598694',
    success (res) {
      
      wx.showToast({
        title: '链接已复制，请通过浏览器前往App Store下载',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

/** 
 * 获取请求用token信息，如果未有当前用户返回undefined
 */
const getToken = () => {
  const currentUser = wx.getStorageSync('CurrentUser');
  if (currentUser) {
    return `Authorization=${currentUser.Token}`;
  }
}

/** 
 * 字母和汉字的校验，符合则返回true
 */
const isValidChineseCharacter = (str) => {
  return /^[A-Za-z\u4e00-\u9fa5\u3400-\u4db5\u{20000}-\u{2a6d6}]+$/gimu.test(str);
}

const setStorageHistoryUsers = (data) => {
  wx.setStorageSync("CurrentUser", data)
  let historyUsers = wx.getStorageSync('HistoryUsers');
  let temp = historyUsers ? historyUsers : [];
  for (let i = 0; i < temp.length; i++) {
    if (temp[i].BarCode == data.BarCode) {
      temp.splice(i, 1);
      break;
    }
  }
  temp.unshift({
    BarCode: data.BarCode,
    Name: data.Name,
    CourseTypeName: data.CourseTypeName
  })
  wx.setStorageSync("HistoryUsers", temp.slice(0, 5))
}

/**
 * 验证邮箱是否正确
 */
const isEmail = function(val) {  
  return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(val);
}

/**
 * 验证图片链接是不是绝对路径
 */
const picUrl = function(apiurl,val){
  // let thisurl = config.host+'image/';
  // let thisurl = 'https://www.bonaxl.com:8094/api/aboard/image/';
   let thisurl= 'https://youjuoss.oss-accelerate.aliyuncs.com/image/'
  if(val){
    return val.includes('http') ? val : thisurl + apiurl + val
  }
}

/**
 * 后台数据null转换成“"
 */
const dataHandleNull = function(data){
  
  for (const key in data) {
    data[key] = data[key]===null?"":data[key];
  }
  return data;
  
}


module.exports = {
  formatTime: formatTime,
  setShareAppMessage: setShareAppMessage,
  getToken: getToken,
  isValidChineseCharacter: isValidChineseCharacter,
  setStorageHistoryUsers,
  isEmail,
  picUrl,
  launchAppCopy,
  dataHandleNull
}